package com.example.gkcircle.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.*;
import android.widget.BaseAdapter;
import android.widget.*;

import com.avos.avoscloud.AVACL;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.bigkoo.alertview.AlertView;
import com.bm.library.PhotoView;
import com.example.gkcircle.App;
import com.example.gkcircle.R;
import com.example.gkcircle.activity.LoginActivity;
import com.example.gkcircle.bean.Wish;
import com.example.gkcircle.db.DBUtil;
import com.example.gkcircle.utils.ActivityUtil;
import com.example.gkcircle.utils.CommonUtil;
import com.example.gkcircle.utils.MyAlertView;
import com.example.gkcircle.utils.PicUtil;
import com.example.gkcircle.utils.UniversalImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * 主页
 * Created by Jehu on 16/3/18.
 */
public class HomeAdapter extends BaseAdapter {


    private List<Wish> mData;
    private Activity mActivity;
    private LayoutInflater inflater;
    private final int DIVIDE_LINE = 0;// 分割线
    private final int CONTENT = 1;// 内容
    private final int MAX_TYPE_LAYOUT = 2;

    public HomeAdapter(Activity activity,List<Wish> data) {
        this.mData=data;
        this.mActivity = activity;
        this.inflater = LayoutInflater.from(mActivity);
    }

    @Override
    public int getItemViewType(int position) {
        switch (position){
            case DIVIDE_LINE:
                return DIVIDE_LINE;
            case CONTENT:
                return CONTENT;
            default:
                return CONTENT;
        }
    }

    @Override
    public int getViewTypeCount() {
        return MAX_TYPE_LAYOUT;
    }

    @Override
    public int getCount() {
        return mData==null?0:mData.size()+1;
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    static class viewHolder{
        ImageView avatar;
        TextView username;
        TextView date;
        TextView content;
        TextView wishCount;
        PhotoView photo;
        ImageButton wishBtn;
        LinearLayout wishLayout;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        int currentPosition=getItemViewType(position);
        //分割线
        if(currentPosition==DIVIDE_LINE){

            convertView = inflater.inflate(R.layout.home_list_divide, null,false);
        //最美心愿内容
        }else if(currentPosition==CONTENT){
            final viewHolder viewHolder;

            if(convertView==null){
                viewHolder=new viewHolder();
                convertView=inflater.inflate(R.layout.home_list_item,null);
                //初始化控件
                viewHolder.avatar=(ImageView)convertView.findViewById(R.id.home_list_item_avatar);
                viewHolder.username=(TextView)convertView.findViewById(R.id.home_list_item_username);
                viewHolder.content=(TextView)convertView.findViewById(R.id.home_list_item_content);
                viewHolder.date=(TextView)convertView.findViewById(R.id.home_list_item_date);
                viewHolder.wishCount=(TextView)convertView.findViewById(R.id.home_list_item_wish_count);
                viewHolder.wishBtn=(ImageButton)convertView.findViewById(R.id.home_list_item_wish_btn);
                viewHolder.wishLayout=(LinearLayout)convertView.findViewById(R.id.home_list_item_wish_layout);
                viewHolder.photo=(PhotoView)convertView.findViewById(R.id.home_list_item_photo);
                convertView.setTag(viewHolder);
            }else {
                viewHolder=(viewHolder)convertView.getTag();
            }

            final Wish wish=mData.get(position-1);
            final AVUser user=wish.getUser();
            viewHolder.content.setText(wish.getContent());

            viewHolder.username.setText(user.get("nickname").toString());
            viewHolder.content.setText(wish.getContent());
            viewHolder.date.setText(wish.getCreatedAt());
            viewHolder.wishCount.setText(wish.getLikeCount()+"");
            //用户头像
            if(null!=user.getAVFile("avatar")){
                int width=mActivity.getResources().getDimensionPixelSize(R.dimen.love_avatar_width);
                //获取缩略图url
                String avatarUrl=user.getAVFile("avatar").getThumbnailUrl(true,width,width);
                UniversalImageLoader.getIntance().displayImage(avatarUrl,viewHolder.avatar,UniversalImageLoader.getAvatarOptions(),UniversalImageLoader.getAnimateFirstDisplayListener());
            }else{
                viewHolder.avatar.setImageResource(R.mipmap.personal_default_user_icon);
            }

            //用户是否点赞过
            if(wish.isLike()){
                viewHolder.wishBtn.setBackground(mActivity.getResources().getDrawable(R.mipmap.wish_pressed_btn));
            }else{
                viewHolder.wishBtn.setBackground(mActivity.getResources().getDrawable(R.mipmap.wish_normal_btn));
            }

            //祝福点赞
            viewHolder.wishLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!DBUtil.getInstance(mActivity).getLikeWish(wish)){
                        like(viewHolder,wish,position-1);
                    }
                }
            });

            //祝福点赞
            viewHolder.wishBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!DBUtil.getInstance(mActivity).getLikeWish(wish)){
                        like(viewHolder,wish,position-1);
                    }
                }
            });
            //宽 >= 高时 横向照片（3:4）
            int firstheight=(App.screenWidth -PicUtil.dip2px(mActivity,20))*3/4;
            //宽 < 高时 竖向照片 (8:7)
            int secondHeight=(App.screenWidth-PicUtil.dip2px(mActivity,20))*8/7;
            if(wish.getPhotoWidth()>=wish.getPhotoHeight()){
                viewHolder.photo.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,firstheight));
            }else{
                viewHolder.photo.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,secondHeight));
            }
            UniversalImageLoader.getIntance().displayImage(wish.getPhotoUrl(), viewHolder.photo, UniversalImageLoader.getPhotorOptions(), UniversalImageLoader.getAnimateFirstDisplayListener());

        }
        return convertView;
    }


    public EditText editText;

    public void like(final viewHolder viewHolder,Wish wish, final int position){
        //判断是否已登录
        if(AVUser.getCurrentUser()==null){
            ActivityUtil.startActivity(mActivity, LoginActivity.class);
            return;
        }
        onLikedListener=new OnLikedListener() {
            @Override
            public void onComplete(boolean isComplete) {
                if(isComplete){
                    App.mHomeList.get(position).setIsLike(true);
                    mData.get(position).setIsLike(true);
                }
            }
        };

        MyAlertView.alertView=new AlertView(null,null, "取消", null, new String[]{"祝愿"}, mActivity, AlertView.Style.Alert,new OnItemClickListener(viewHolder,wish,position));
        ViewGroup extView = (ViewGroup) LayoutInflater.from(mActivity).inflate(R.layout.love_wish_like_dialog,null);
        editText = (EditText) extView.findViewById(R.id.love_wish_like_dialog_edit);
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean focus) {
                //输入框出来则往上移动
                boolean isOpen = CommonUtil.isShowSoftInputView(mActivity);
                MyAlertView.alertView.setMarginBottom(isOpen && focus ? 80 : 0);
            }
        });
        MyAlertView.alertView.addExtView(extView);
        MyAlertView.alertView.show();
    }

    public OnLikedListener onLikedListener;
    public interface OnLikedListener{
        void onComplete(boolean isComplete);
    }
    public class OnItemClickListener implements com.bigkoo.alertview.OnItemClickListener{

        private viewHolder viewHolder;
        private Wish wish;
        private int position;

        public OnItemClickListener(viewHolder viewHolder,Wish wish,int position){
            this.viewHolder=viewHolder;
            this.wish=wish;
            this.position=position;
        }
        @Override
        public void onItemClick(final Object o, int position) {
            CommonUtil.closeSoftInputViewFromWindow(mActivity,editText,MyAlertView.alertView);
            //判断是否是拓展窗口View，而且点击的是非取消按钮
            if(o == MyAlertView.alertView && position != AlertView.CANCELPOSITION){
                String content=editText.getText().toString();
                if(content.isEmpty()){
                    return;
                }
                AVObject comment=new AVObject("WishComment");
                comment.put("content",content);
                comment.put("user",AVUser.getCurrentUser());
                comment.put("wish",AVObject.createWithoutData("Wish", wish.getObjectId()));
                //添加权限
                AVACL acl=new AVACL();
                acl.setPublicReadAccess(true);
                //设置评论仅发布者和评论者可写
                acl.setWriteAccess(AVUser.getCurrentUser(), true);
                acl.setWriteAccess(wish.getUser(), true);
                comment.setACL(acl);
                comment.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(AVException e) {
                        if(null==e){
                            viewHolder.wishCount.setText((wish.getLikeCount() + 1) + "");
                            viewHolder.wishBtn.setBackground(mActivity.getResources().getDrawable(R.mipmap.wish_pressed_btn));
                            final AVObject objWish = AVObject.createWithoutData("Likes",wish.getLikesObjectId());
                            objWish.setFetchWhenSave(true);
                            objWish.increment("likeCount");
                            objWish.saveInBackground(new SaveCallback() {
                                @Override
                                public void done(AVException e) {
                                    if(e!=null)return;
                                    DBUtil.getInstance(mActivity).likeWish(wish);
                                    viewHolder.wishCount.setText(objWish.get("likeCount") + "");
                                    if(onLikedListener!=null){
                                        onLikedListener.onComplete(true);
                                    }
                                }
                            });
                        }else{
                            if(onLikedListener!=null){
                                onLikedListener.onComplete(false);
                            }
                        }
                    }
                });
            }
        }
    }


}
